;
(function(win, doc) {
    var oImgList = doc.getElementsByClassName('J_imgList')[0],
        data = JSON.parse(doc.getElementById('J_data').innerHTML),
        imgTpl = doc.getElementById('J_imgTpl').innerHTML,
        oImg = doc.getElementsByClassName('list-img')

    var init = function() {
        oImgList.innerHTML = renderList(data)
        bindEvent();
        setTimeout(() => {
            window.scrollTo(0, 0)
        }, 150)
    }

    function bindEvent() {
        window.onload = window.onscroll = throttle(imgLazyLoad(oImg), 800)
    }

    function renderList(data) {
        var list = '';
        data.forEach((elem) => {
            list += imgTpl.replace(/{{(.*?)}}/g, function(node, key) {
                return {
                    img: elem.img,
                    name: elem.name
                }[key]
            })
        })
        return list
    }

    init()
})(window, document);


function imgLazyLoad(image) {
    var imgLen = image.length,
        n = 0
    return function() {
        var cHeight = document.documentElement.clientHeight,
            sTop = document.documentElement.scrollTop || document.body.scrollTop,
            imgItem;
        for (let i = n; i < imgLen; i++) {
            imgItem = image[i]
            if (imgItem.offsetTop < cHeight + sTop) {
                imgItem.src = imgItem.getAttribute('data-src');
                imgItem.removeAttribute('data-src')
                n++
            }
        }
    }
}


function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        //一直在删除timeout
        if (timeout) clearTimeout(timeout)
            //最后一次计时，不会清除
        timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait)
    }
}